package com.youlu.campus.web.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class ParseXMLUtils {
	
	private static final Logger logger = LoggerFactory.getLogger(ParseXMLUtils.class);

    /**
     * XML格式字符串转换为Map
     *
     * @param strXML XML字符串
     * @return XML数据转换后的Map
     * @throws Exception
     */
    public static Map<String, String> xmlToMap(String strXML) throws Exception {
        try {
            Map<String, String> data = new HashMap<String, String>();
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            InputStream stream = new ByteArrayInputStream(strXML.getBytes("UTF-8"));
            Document doc = documentBuilder.parse(stream);
            doc.getDocumentElement().normalize();
            NodeList nodeList = doc.getDocumentElement().getChildNodes();
            for (int idx = 0; idx < nodeList.getLength(); ++idx) {
                Node node = nodeList.item(idx);
                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    Element element = (Element) node;
                    data.put(element.getNodeName(), element.getTextContent());
                }
            }
            try {
                stream.close();
            } catch (Exception ex) {
                // do nothing
            }
            return data;
        } catch (Exception ex) {
        	logger.error("Invalid XML, can not convert to map. Error message: {}. XML content: {}", ex.getMessage(), strXML);
            throw ex;
        }

    }

    /**
     * 将Map转换为XML格式的字符串
     *
     * @param data Map类型数据
     * @return XML格式的字符串
     * @throws Exception
     */
    public static String mapToXml(Map<String, String> data) throws Exception {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder= documentBuilderFactory.newDocumentBuilder();
        Document document = documentBuilder.newDocument();
        Element root = document.createElement("xml");
        document.appendChild(root);
        for (String key: data.keySet()) {
            String value = data.get(key);
            if (value == null) {
                value = "";
            }
            value = value.trim();
            Element filed = document.createElement(key);
            filed.appendChild(document.createTextNode(value));
            root.appendChild(filed);
        }
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        DOMSource source = new DOMSource(document);
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        StringWriter writer = new StringWriter();
        StreamResult result = new StreamResult(writer);
        transformer.transform(source, result);
        String output = writer.getBuffer().toString(); //.replaceAll("\n|\r", "");
        try {
            writer.close();
        }
        catch (Exception ex) {
        }
        return output;
    }
	
	/**
	 * 1、DOM解析
	 * 
	 * @throws Exception
	 */
	public static Object beginXMLParse(String xml, Class<?> clazz) throws Exception {
		Document document = null;
		// 实例化一个xml创建工厂类
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		// 解析xml文件的解析器
		DocumentBuilder db = dbf.newDocumentBuilder();

		StringReader sr = new StringReader(xml);
		InputSource is = new InputSource(sr);

		document = db.parse(is);

		Element root = document.getDocumentElement();
		NodeList childNodes = root.getChildNodes();
		Object newInstance = clazz.newInstance();
		Field[] field = clazz.getDeclaredFields();
		try {
			for (int i = 0; i < childNodes.getLength(); i++) {
				Node node = childNodes.item(i);
				String nodeName = node.getNodeName();
				String textContent = node.getTextContent();
				for (int j = 0; j < field.length; j++) { // 遍历所有属性
					String name = field[j].getName(); // 获取属性的名字
					if (name.equals(nodeName)) {

						name = name.substring(0, 1).toUpperCase() + name.substring(1); // 将属性的首字符大写，方便构造get，set方法
						String type = field[j].getGenericType().toString(); // 获取属性的类型
						if (type.equals("class java.lang.String")) { // 如果type是类类型，则前面包含"class
																		// "，后面跟类名
							Method method = clazz.getMethod("set" + name, String.class);
							method.invoke(newInstance, textContent);
						}
						if (type.equals("class java.lang.Integer")) {
							Method m = clazz.getMethod("set" + name, Integer.class);
							m.invoke(newInstance, Integer.parseInt(textContent));
						}
						if (type.equals("class java.lang.Boolean")) {
							Method m = clazz.getMethod("set" + name, Boolean.class);
							m.invoke(newInstance, Boolean.valueOf(textContent));
						}
						if (type.equals("class java.lang.Long")) {
							Method m = clazz.getMethod("set" + name, Long.class);
							m.invoke(newInstance, Long.parseLong(textContent));
						}
					}
					// 如果有需要,可以仿照上面继续进行扩充,再增加对其它类型的判断
				}
			}
		} catch (NoSuchMethodException e) {
			logger.error("xml解析异常", e);
		} catch (SecurityException e) {
			logger.error("xml解析异常", e);
		} catch (IllegalAccessException e) {
			logger.error("xml解析异常", e);
		} catch (IllegalArgumentException e) {
			logger.error("xml解析异常", e);
		} catch (InvocationTargetException e) {
			logger.error("xml解析异常", e);
		}

		return newInstance;
	}
}
